<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    SSAO algorithm from http://www.nutty.ca/?page_id=352&link=ssao
 -->
<html>
<head>
    <title>WebGL 2 Example: Screen Space Ambient Occlusion</title>
    <meta charset="utf-8">
    <script src="utils/gl-matrix.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="css/webgl2examples.css">
    <style>
        #ssao-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <div id="example-title">
        <header>WebGL 2 Example: Screen Space Ambient Occlusion</header>
        <div id="features">
            Features: Vertex Arrays, Uniform Buffers, Immutable Textures, Multiple Render Targets, Float Textures, texelFetch, Hardware Instancing, EXT_color_buffer_float
        </div>
        <div>
            <a href="https://github.com/tsherif/webgl2examples/blob/master/ssao.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <div id="ssao-controls">
        Enable SSAO: <input id="ssao-toggle" type="checkbox" checked>
    </div>
    <script type="x-shader/vs" id="vertex-colorgeo">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec3 normal;
        layout(location=3) in vec4 color;
        layout(location=4) in mat4 modelMatrix;
        
        uniform SceneUniforms {
            mat4 uViewMatrix;
            mat4 uProjection;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };       
        
        out vec4 vPosition;
        out vec2 vUV;
        out vec4 vNormal;
        out vec4 vViewPosition;
        out vec4 vViewNormal;

        void main() {
            vPosition = modelMatrix * position;
            vNormal = modelMatrix * vec4(normal, 0.0);
            vUV = uv;
            vViewPosition = uViewMatrix * vPosition;
            vViewNormal = uViewMatrix * vNormal;
            gl_Position = uProjection * vViewPosition;
          }
    </script>
    <script type="x-shader/fs" id="fragment-colorgeo">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        uniform SceneUniforms {
            mat4 uViewMatrix;
            mat4 uProjection;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };

        uniform sampler2D uTexture;
        
        in vec4 vPosition;
        in vec2 vUV;
        in vec4 vNormal;
        in vec4 vViewPosition;
        in vec4 vViewNormal;

        layout(location=0) out vec4 color;
        layout(location=1) out vec4 viewPosition;
        layout(location=2) out vec4 viewNormal;

        void main() {
            vec3 position = vPosition.xyz;
            vec3 normal = normalize(vNormal.xyz);
            vec2 uv = vUV;

            vec4 baseColor = texture(uTexture, uv);
            vec3 eyeDirection = normalize(uEyePosition.xyz - position);
            vec3 lightVec = uLightPosition.xyz - position;
            vec3 lightDirection = normalize(lightVec);
            vec3 reflectionDirection = reflect(-lightDirection, normal);
            float nDotL = max(dot(lightDirection, normal), 0.0);
            float diffuse = nDotL;
            float ambient = 0.2;
            float specular = pow(max(dot(reflectionDirection, eyeDirection), 0.0), 20.0);

            color = vec4((ambient + diffuse + specular) * baseColor.rgb, 1.0);
            viewPosition = vViewPosition;
            viewNormal = vViewNormal;
        }
    </script>
    <script type="x-shader/vs" id="vertex-quad">
        #version 300 es

        layout(location=0) in vec4 position;
        
        void main() {
            gl_Position = position;
        }
    </script>

    <script type="x-shader/fs" id="fragment-ssao">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        #define SIN45 0.707107

        uniform SSAOUniforms {
            float uSampleRadius;
            float uBias;
            vec2 uAttenuation;
            vec2 uDepthRange;
        };

        uniform sampler2D uPositionBuffer;
        uniform sampler2D uNormalBuffer;
        uniform sampler2D uNoiseBuffer;
        
        out float occlusion;

        float getOcclusion(vec3 position, vec3 normal, ivec2 fragCoord) {
            vec3 occluderPosition = texelFetch(uPositionBuffer, fragCoord, 0).xyz;
            vec3 positionVec = occluderPosition - position;
            float intensity = max(dot(normal, normalize(positionVec)) - uBias, 0.0);
        
            float attenuation = 1.0 / (uAttenuation.x + uAttenuation.y * length(positionVec));

            return intensity * attenuation;
        }

        void main() {
            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            vec3 position = texelFetch(uPositionBuffer, fragCoord, 0).xyz;
            vec3 normal = texelFetch(uNormalBuffer, fragCoord, 0).xyz;
            vec2 rand = normalize(texelFetch(uNoiseBuffer, fragCoord, 0).xy);
            float depth = (length(position) - uDepthRange.x) / (uDepthRange.y - uDepthRange.x);

            float kernelRadius = uSampleRadius * (1.0 - depth);

            vec2 kernel[4];
            kernel[0] = vec2(0.0, 1.0);
            kernel[1] = vec2(1.0, 0.0);
            kernel[2] = vec2(0.0, -1.0);
            kernel[3] = vec2(-1.0, 0.0);

            occlusion = 0.0;
            for (int i = 0; i < 4; ++i) {
                vec2 k1 = reflect(kernel[i], rand);
                vec2 k2 = vec2(k1.x * SIN45 - k1.y * SIN45, k1.x * SIN45 + k1.y * SIN45);

                k1 *= kernelRadius;
                k2 *= kernelRadius;

                occlusion += getOcclusion(position, normal, fragCoord + ivec2(k1));
                occlusion += getOcclusion(position, normal, fragCoord + ivec2(k2 * 0.75));
                occlusion += getOcclusion(position, normal, fragCoord + ivec2(k1 * 0.5));
                occlusion += getOcclusion(position, normal, fragCoord + ivec2(k2 * 0.25));
            }

            occlusion = clamp(occlusion / 16.0, 0.0, 1.0);
        }
    </script>
    <script type="x-shader/fs" id="fragment-aoblend">
        #version 300 es
        precision highp float;

        uniform sampler2D uColorBuffer;
        uniform sampler2D uOcclusionBuffer;

        out vec4 color;
        void main() {
            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            color = vec4(clamp(texelFetch(uColorBuffer, fragCoord, 0).rgb - texelFetch(uOcclusionBuffer, fragCoord, 0).r, 0.0, 1.0), 1.0);
        }
    </script>
     <script type="x-shader/fs" id="fragment-color">
        #version 300 es
        precision highp float;

        uniform sampler2D uColorBuffer;

        out vec4 color;

        void main() {
            color = vec4(texelFetch(uColorBuffer, ivec2(gl_FragCoord.xy), 0).rgb, 1.0);
        }
    </script>
    <script>
        var ssaoEnabled = true;

        document.getElementById("ssao-toggle").addEventListener("change", function() {
            ssaoEnabled = this.checked;
        });

        var canvas = document.getElementById("gl-canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var gl = canvas.getContext("webgl2");

        if (!gl) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        if (!gl.getExtension("EXT_color_buffer_float")) {
            console.error("FLOAT color buffer not available");
            document.body.innerHTML = "This example requires EXT_color_buffer_float which is unavailable on this system."
        }

        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.enable(gl.DEPTH_TEST);

        /////////////////////////
        // SCENE DATA
        /////////////////////////

        var NEAR = 0.1;
        var FAR = 10.0;

        var NUM_SPHERES = 32;
        var NUM_PER_ROW = 8;
        var RADIUS = 0.6;
        var spheres = new Array(NUM_SPHERES);

        var modelMatrixData = new Float32Array(NUM_SPHERES * 16);

        for (var i = 0; i < NUM_SPHERES; ++i) {
            var angle = 2 * Math.PI * (i % NUM_PER_ROW) / NUM_PER_ROW;
            var x = Math.sin(angle) * RADIUS;
            var y = Math.floor(i / NUM_PER_ROW) / (NUM_PER_ROW / 4) - 0.75;
            var z = Math.cos(angle) * RADIUS;
            spheres[i] = {
                scale: [0.8, 0.8, 0.8],
                rotate: [0, 0, 0], // Will be used for global rotation
                translate: [x, y, z],
                modelMatrix: mat4.create()
            };
        }

        var numNoisePixels = gl.drawingBufferWidth * gl.drawingBufferHeight;
        var noiseTextureData = new Float32Array(numNoisePixels * 2);

        for (var i = 0; i < numNoisePixels; ++i) {
            var index = i * 2;
            noiseTextureData[index]     = Math.random() * 2.0 - 1.0;
            noiseTextureData[index + 1] = Math.random() * 2.0 - 1.0;
        }

        var depthRange = vec2.fromValues(NEAR, FAR);

        /////////////////////////
        // COLOR/GEO PROGRAM
        /////////////////////////

        var colorgeoVsSource =  document.getElementById("vertex-colorgeo").text.trim();
        var colorgeoFsSource =  document.getElementById("fragment-colorgeo").text.trim();
        
        var colorgeoVertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(colorgeoVertexShader, colorgeoVsSource);
        gl.compileShader(colorgeoVertexShader);

        if (!gl.getShaderParameter(colorgeoVertexShader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(colorgeoVertexShader));
        }

        var colorgeoFragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(colorgeoFragmentShader, colorgeoFsSource);
        gl.compileShader(colorgeoFragmentShader);

        if (!gl.getShaderParameter(colorgeoFragmentShader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(colorgeoFragmentShader));
        }

        var colorGeoProgram = gl.createProgram();
        gl.attachShader(colorGeoProgram, colorgeoVertexShader);
        gl.attachShader(colorGeoProgram, colorgeoFragmentShader);
        gl.linkProgram(colorGeoProgram);

        if (!gl.getProgramParameter(colorGeoProgram, gl.LINK_STATUS)) {
            console.error(gl.getProgramInfoLog(colorGeoProgram));
        }

        /////////////////////
        // SSAO PROGRAMS
        /////////////////////

        var quadVsSource =  document.getElementById("vertex-quad").text.trim();
        var ssaoFsSource = document.getElementById("fragment-ssao").text.trim();
        var aoBlendFsSource = document.getElementById("fragment-aoblend").text.trim();
        var noSSAOFsSource = document.getElementById("fragment-color").text.trim();

        var quadVertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(quadVertexShader, quadVsSource);
        gl.compileShader(quadVertexShader);

        if (!gl.getShaderParameter(quadVertexShader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(quadVertexShader));
        }

        var ssaoFragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(ssaoFragmentShader, ssaoFsSource);
        gl.compileShader(ssaoFragmentShader);

        if (!gl.getShaderParameter(ssaoFragmentShader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(ssaoFragmentShader));
        }

        var aoBlendFragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(aoBlendFragmentShader, aoBlendFsSource);
        gl.compileShader(aoBlendFragmentShader);

        if (!gl.getShaderParameter(aoBlendFragmentShader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(aoBlendFragmentShader));
        }

        var noSSAOFragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(noSSAOFragmentShader, noSSAOFsSource);
        gl.compileShader(noSSAOFragmentShader);

        if (!gl.getShaderParameter(noSSAOFragmentShader, gl.COMPILE_STATUS)) {
            console.error(gl.getShaderInfoLog(noSSAOFragmentShader));
        }

        // Calculate occlusion
        var ssaoProgram = gl.createProgram();
        gl.attachShader(ssaoProgram, quadVertexShader);
        gl.attachShader(ssaoProgram, ssaoFragmentShader);
        gl.linkProgram(ssaoProgram);

        if (!gl.getProgramParameter(ssaoProgram, gl.LINK_STATUS)) {
            console.error(gl.getProgramInfoLog(ssaoProgram));
        }

        // Blend color/occlusion
        var aoBlendProgram = gl.createProgram();
        gl.attachShader(aoBlendProgram, quadVertexShader);
        gl.attachShader(aoBlendProgram, aoBlendFragmentShader);
        gl.linkProgram(aoBlendProgram);

        if (!gl.getProgramParameter(aoBlendProgram, gl.LINK_STATUS)) {
            console.error(gl.getProgramInfoLog(aoBlendProgram));
        }

        // SSAO disabled
        var noSSAOProgram = gl.createProgram();
        gl.attachShader(noSSAOProgram, quadVertexShader);
        gl.attachShader(noSSAOProgram, noSSAOFragmentShader);
        gl.linkProgram(noSSAOProgram);

        if (!gl.getProgramParameter(noSSAOProgram, gl.LINK_STATUS)) {
            console.error(gl.getProgramInfoLog(noSSAOProgram));
        }

        /////////////////////////
        // GET UNIFORM LOCATIONS
        /////////////////////////

        var sceneUniformsLocation = gl.getUniformBlockIndex(colorGeoProgram, "SceneUniforms");
        gl.uniformBlockBinding(colorGeoProgram, sceneUniformsLocation, 0);

        var modelMatrixLocation = gl.getUniformLocation(colorGeoProgram, "uModel");
        var textureLocation = gl.getUniformLocation(colorGeoProgram, "uTexture");

        var ssaoUniformsLocation = gl.getUniformBlockIndex(ssaoProgram, "SSAOUniforms");
        gl.uniformBlockBinding(ssaoProgram, ssaoUniformsLocation, 1);

        var positionBufferLocation = gl.getUniformLocation(ssaoProgram, "uPositionBuffer");
        var normalBufferLocation = gl.getUniformLocation(ssaoProgram, "uNormalBuffer");
        var noiseBufferLocation = gl.getUniformLocation(ssaoProgram, "uNoiseBuffer");

        var colorBufferLocation = gl.getUniformLocation(aoBlendProgram, "uColorBuffer");
        var occlustionBufferLocation = gl.getUniformLocation(aoBlendProgram, "uOcclusionBuffer");

        var noSSAOColorBufferLocation = gl.getUniformLocation(noSSAOProgram, "uColorBuffer");

        ////////////////////////////////
        //  SET UP FRAMEBUFFERS
        ////////////////////////////////

        var colorGeoBuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, colorGeoBuffer);
        gl.activeTexture(gl.TEXTURE0);

        var colorTarget = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, colorTarget);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, gl.drawingBufferWidth, gl.drawingBufferHeight);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTarget, 0);

        var positionTarget = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, positionTarget);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA16F, gl.drawingBufferWidth, gl.drawingBufferHeight);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, positionTarget, 0);

        var normalTarget = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, normalTarget);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA16F, gl.drawingBufferWidth, gl.drawingBufferHeight);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT2, gl.TEXTURE_2D, normalTarget, 0);

        var depthTarget = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, depthTarget);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texStorage2D(gl.TEXTURE_2D, 1, gl.DEPTH_COMPONENT16, gl.drawingBufferWidth, gl.drawingBufferHeight);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTarget, 0);

         gl.drawBuffers([
            gl.COLOR_ATTACHMENT0,
            gl.COLOR_ATTACHMENT1,
            gl.COLOR_ATTACHMENT2
        ]);

        var occlusionBuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, occlusionBuffer);

        var occlusionTarget = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, occlusionTarget);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, gl.drawingBufferWidth, gl.drawingBufferHeight);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, occlusionTarget, 0);

        gl.bindFramebuffer(gl.FRAMEBUFFER, null);

        /////////////////////
        // SET UP GEOMETRY
        /////////////////////

        var sphere = utils.createSphere({radius: 0.5});
        var numVertices = sphere.positions.length / 3;

        var sphereArray = gl.createVertexArray();
        gl.bindVertexArray(sphereArray);

        var positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, sphere.positions, gl.STATIC_DRAW);
        gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(0);

        var uvBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, sphere.uvs, gl.STATIC_DRAW);
        gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(1);

        var normalBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, sphere.normals, gl.STATIC_DRAW);
        gl.vertexAttribPointer(2, 3, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(2);

        // Columns of matrix as separate attributes for instancing
        var matrixBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, matrixBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, modelMatrixData, gl.DYNAMIC_DRAW);
        gl.vertexAttribPointer(4, 4, gl.FLOAT, false, 64, 0);
        gl.vertexAttribPointer(5, 4, gl.FLOAT, false, 64, 16);
        gl.vertexAttribPointer(6, 4, gl.FLOAT, false, 64, 32);
        gl.vertexAttribPointer(7, 4, gl.FLOAT, false, 64, 48);

        gl.vertexAttribDivisor(4, 1);
        gl.vertexAttribDivisor(5, 1);
        gl.vertexAttribDivisor(6, 1);
        gl.vertexAttribDivisor(7, 1);

        gl.enableVertexAttribArray(4);
        gl.enableVertexAttribArray(5);
        gl.enableVertexAttribArray(6);
        gl.enableVertexAttribArray(7);

        var indices = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, sphere.indices, gl.STATIC_DRAW);

        // Quad for screen-space passes
        var quadArray = gl.createVertexArray();
        gl.bindVertexArray(quadArray);

        var quadPositionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, quadPositionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
            -1, 1,
            -1, -1,
            1, -1,
            -1, 1,
            1, -1,
            1, 1,
        ]), gl.STATIC_DRAW);
        gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(0);

        //////////////////////
        // SET UP UNIFORMS
        //////////////////////

        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, NEAR, FAR);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(0, 0.8, 2);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var lightPosition = vec3.fromValues(1, 1, 2);
        
        var sceneUniformData = new Float32Array(40);
        sceneUniformData.set(viewMatrix);
        sceneUniformData.set(projMatrix, 16);
        sceneUniformData.set(eyePosition, 32);
        sceneUniformData.set(lightPosition, 36);

        var sceneUniformBuffer = gl.createBuffer();
        gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, sceneUniformBuffer);
        gl.bufferData(gl.UNIFORM_BUFFER, sceneUniformData, gl.STATIC_DRAW);

        var ssaoUniformData = new Float32Array(8);
        ssaoUniformData[0] = 16.0; // sample radius
        ssaoUniformData[1] = 0.04; // bias
        ssaoUniformData.set(vec2.fromValues(1, 1), 2); // attenuation
        ssaoUniformData.set(depthRange, 4);

        var ssaoUniformBuffer = gl.createBuffer();
        gl.bindBufferBase(gl.UNIFORM_BUFFER, 1, ssaoUniformBuffer);
        gl.bufferData(gl.UNIFORM_BUFFER, ssaoUniformData, gl.STATIC_DRAW);

        var image = new Image();

        image.onload = function() {

            ///////////////////////
            // BIND TEXTURES
            ///////////////////////

            var texture = gl.createTexture();
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, texture);

            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
            
            var levels = levels = Math.floor(Math.log2(Math.max(this.width, this.height))) + 1;
            gl.texStorage2D(gl.TEXTURE_2D, levels, gl.RGBA8, image.width, image.height);
            gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, gl.RGBA, gl.UNSIGNED_BYTE, image);
            gl.generateMipmap(gl.TEXTURE_2D);

            var noiseTexture = gl.createTexture();
            gl.activeTexture(gl.TEXTURE1);
            gl.bindTexture(gl.TEXTURE_2D, noiseTexture);

            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RG16F, gl.drawingBufferWidth, gl.drawingBufferHeight);
            gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RG, gl.FLOAT, noiseTextureData);

            gl.activeTexture(gl.TEXTURE2);
            gl.bindTexture(gl.TEXTURE_2D, colorTarget);

            gl.activeTexture(gl.TEXTURE3);
            gl.bindTexture(gl.TEXTURE_2D, positionTarget);

            gl.activeTexture(gl.TEXTURE4);
            gl.bindTexture(gl.TEXTURE_2D, normalTarget);

            gl.activeTexture(gl.TEXTURE5);
            gl.bindTexture(gl.TEXTURE_2D, occlusionTarget);

            gl.useProgram(colorGeoProgram);
            gl.uniform1i(textureLocation, 0);

            gl.useProgram(ssaoProgram);
            gl.uniform1i(positionBufferLocation, 3);
            gl.uniform1i(normalBufferLocation, 4);
            gl.uniform1i(noiseBufferLocation, 1);
            
            gl.useProgram(aoBlendProgram);
            gl.uniform1i(colorBufferLocation, 2);
            gl.uniform1i(occlustionBufferLocation, 5);

            gl.useProgram(noSSAOProgram);
            gl.uniform1i(noSSAOColorBufferLocation, 2);

            var rotationMatrix = mat4.create();

            function draw() {

                ////////////////////
                // DRAW BOXES
                ////////////////////

                gl.bindFramebuffer(gl.FRAMEBUFFER, colorGeoBuffer);
                gl.useProgram(colorGeoProgram);
                gl.bindVertexArray(sphereArray);

                for (var i = 0, len = spheres.length; i < len; ++i) {
                    spheres[i].rotate[1] += 0.002;

                    utils.xformMatrix(spheres[i].modelMatrix, spheres[i].translate, null, spheres[i].scale);
                    mat4.fromYRotation(rotationMatrix, spheres[i].rotate[1]);
                    mat4.multiply(spheres[i].modelMatrix, rotationMatrix, spheres[i].modelMatrix);
                
                    modelMatrixData.set(spheres[i].modelMatrix, i * 16);
                }

                gl.bindBuffer(gl.ARRAY_BUFFER, matrixBuffer);
                gl.bufferSubData(gl.ARRAY_BUFFER, 0, modelMatrixData);
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
                gl.drawElementsInstanced(gl.TRIANGLES, sphere.indices.length, gl.UNSIGNED_SHORT, 0, spheres.length);

                gl.bindVertexArray(quadArray);

                if (ssaoEnabled) {
                    //////////////////
                    // OCCLUSION PASS
                    //////////////////

                    gl.bindFramebuffer(gl.FRAMEBUFFER, occlusionBuffer);
                    gl.useProgram(ssaoProgram);
                    gl.drawArrays(gl.TRIANGLES, 0, 6);

                    //////////////////
                    // BLEND PASS
                    //////////////////

                    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
                    gl.useProgram(aoBlendProgram);
                    gl.drawArrays(gl.TRIANGLES, 0, 6);
                } else {
                    ///////////////////////
                    // DRAW W/O OCCLUSION
                    ///////////////////////

                    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
                    gl.useProgram(noSSAOProgram);
                    gl.drawArrays(gl.TRIANGLES, 0, 6);
                }

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        }

        image.src = "img/khronos_webgl.png";

    </script>
    <a href="https://github.com/tsherif/webgl2examples" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
</body>
</html>
